package cn.yunyichina.provider.pay.service.impl;

import cn.yunyichina.provider.framework.dubbo.service.AlipayService;
import cn.yunyichina.provider.iface.entity.alipay.AlipayFacepayMedicalCardQueryRequest;
import cn.yunyichina.provider.iface.entity.alipay.AlipayFacepayMedicalCardQueryResponse;
import cn.yunyichina.provider.iface.entity.alipay.AlipayWebpayMedicalCardQueryRequest;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.pay.alipay.MedicareResponse;
import cn.yunyichina.provider.iface.entity.pay.alipay.MedicareVo;
import cn.yunyichina.provider.pay.constant.AppType;
import cn.yunyichina.provider.pay.constant.Medicare;
import cn.yunyichina.provider.pay.constant.ResponseEnum;
import cn.yunyichina.provider.pay.entity.PaymentSetting;
import cn.yunyichina.provider.pay.exception.PaySettingNotFoundException;
import cn.yunyichina.provider.pay.service.BaseMedicareService;
import cn.yunyichina.provider.pay.service.MedicareService;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class MedicareServiceImpl extends BaseMedicareService implements MedicareService {

    private static final Logger logger = LoggerFactory.getLogger(MedicareServiceImpl.class);

    @Override
    public ResponseObject queryMedicare(String json) {
        logger.info("MedicareServiceImpl.queryMedicare.json -> {}", json);

        ResponseObject response = new ResponseObject();
        try {
            Map<String, String> params = JSON.parseObject(json, Map.class);
            String appType = params.get("app_type");

            switch (AppType.valueOf(appType)) {
                case WECHAT:
                    return response.buildResultCodeAndMessage(
                            ResponseEnum.UNSUPPORTED.getCode(),
                            ResponseEnum.UNSUPPORTED.getMessage()
                    );
                case ALIPAY:
                    String queryScene = params.get("query_scene");

                    switch (Medicare.QueryScene.valueOf(queryScene)) {
                        case WEBPAY:
                            if (!checkAlipayWebpayMedicalCardQueryParameters(params))
                                return response.buildResultCodeAndMessage(
                                        ResponseEnum.MEDICAL_CARD_INVALID_PARAMETERS.getCode(),
                                        ResponseEnum.MEDICAL_CARD_INVALID_PARAMETERS.getMessage()
                                );

                            AlipayWebpayMedicalCardQueryRequest webpayQueryRequest = buildAlipayWebpayMedicalCardQueryParameters(params);
                            logger.info("MedicareServiceImpl.queryMedicare.webpayQueryRequest -> {}", JsonUtils.toJsonString(webpayQueryRequest));

                            ResCommon<Object> webpayQueryResponse = AlipayService.getAlipayClient().queryAlipayWebpayMedicare(webpayQueryRequest);
                            logger.info("MedicareServiceImpl.queryMedicare.webpayQueryResponse -> {}", JsonUtils.toJsonString(webpayQueryResponse));

                            return response.buildResultCodeAndMessageAndResult(webpayQueryResponse.getResultCode(), webpayQueryResponse.getResultMessage(), webpayQueryResponse.getResult());
                        case FACEPAY:
                            if (!checkAlipayFacepayMedicalCardQueryParameters(params))
                                return response.buildResultCodeAndMessage(
                                        ResponseEnum.MEDICAL_CARD_INVALID_PARAMETERS.getCode(),
                                        ResponseEnum.MEDICAL_CARD_INVALID_PARAMETERS.getMessage()
                                );

                            AlipayFacepayMedicalCardQueryRequest facepayQueryRequest = buildAlipayFacepayMedicalCardQueryParameters(params);
                            logger.info("MedicareServiceImpl.queryMedicare.facepayQueryRequest -> {}", JsonUtils.toJsonString(facepayQueryRequest));

                            ResCommon<AlipayFacepayMedicalCardQueryResponse> facepayQueryResponse = AlipayService.getAlipayClient().queryAlipayFacepayMedicare(facepayQueryRequest);
                            logger.info("MedicareServiceImpl.queryMedicare.facepayQueryResponse -> {}", JsonUtils.toJsonString(facepayQueryResponse));

                            return response.buildResultCodeAndMessageAndResult(facepayQueryResponse.getResultCode(), facepayQueryResponse.getResultMessage(), facepayQueryResponse.getResult());
                        default:
                            return response.buildResultCodeAndMessage(
                                    ResponseEnum.UNSUPPORTED.getCode(),
                                    ResponseEnum.UNSUPPORTED.getMessage()
                            );
                    }
                default:
                    return response.buildResultCodeAndMessage(
                            ResponseEnum.UNSUPPORTED.getCode(),
                            ResponseEnum.UNSUPPORTED.getMessage()
                    );
            }
        } catch (PaySettingNotFoundException e) {
            logger.error("MedicareServiceImpl.queryMedicare.PaySettingNotFoundException", e);
            return response.buildResultCodeAndMessage(
                    ResponseEnum.PAY_SETTING_NOT_FOUND.getCode(),
                    ResponseEnum.PAY_SETTING_NOT_FOUND.getMessage()
            );
        } catch (Exception e) {
            logger.error("MedicareServiceImpl.queryMedicare.Exception", e);
            return response.buildResultCodeAndMessage(
                    ResponseEnum.MEDICAL_CARD_QUERY_EXCEPTION.getCode(),
                    ResponseEnum.MEDICAL_CARD_QUERY_EXCEPTION.getMessage()
            );
        }
    }

    /**
     * 阿里支付宝医保支付查询卡
     *
     * @param dataMap
     * @return
     * @throws Exception
     */
    private ResponseObject queryAlipayMedicare(Map<String, String> dataMap) throws Exception {
        logger.info("MedicareServiceImpl.queryAlipayFacepayMedicare.dataMap -> {}", JSON.toJSONString(dataMap));
        ResponseObject response = new ResponseObject();
        MedicareVo vo = new MedicareVo();
        vo.setAppId(dataMap.get("app_id"));
        vo.setAuthCode(dataMap.get("auth_code"));
        vo.setReturnUrl(dataMap.get("return_url"));

        PaymentSetting paymentSetting = this.getPaymentSetting(dataMap.get("app_id"));
        vo.setAlipayPublicKey(paymentSetting.getPublicKey());
        vo.setPrivateKey(paymentSetting.getPrivateKey());

        ResCommon<MedicareResponse> resCommon = AlipayService.getAlipayClient().queryAlipayFacepayMedicare(vo);
        logger.info("MedicareServiceImpl.queryAlipayFacepayMedicare.resCommon -> {}", JSON.toJSONString(resCommon));
        response.setResultCodeAndMessageAndResult(resCommon.getResultCode(), resCommon.getResultMessage(), resCommon.getResult());
        return response;
    }

    /**
     * 阿里支付宝医保支付查询卡
     *
     * @param dataMap
     * @return
     * @throws Exception
     */
    private ResponseObject queryAlipayMedicareTest(Map<String, String> dataMap) throws Exception {
        logger.info("MedicareServiceImpl.queryAlipayMedicareTest.dataMap -> {}", JSON.toJSONString(dataMap));
        ResponseObject response = new ResponseObject();
        MedicareVo vo = new MedicareVo();
        vo.setAppId(dataMap.get("app_id"));
        vo.setAuthCode(dataMap.get("auth_code"));
        vo.setReturnUrl(dataMap.get("return_url"));

//        PaymentSetting paymentSetting = this.getPaymentSetting(dataMap.get("app_id"));
        vo.setAlipayPublicKey(PUBLIC_KEY);
        vo.setPrivateKey(PRIVATE_KEY);

        ResCommon<MedicareResponse> resCommon = AlipayService.getAlipayClient().queryAlipayFacepayMedicare(vo);
        logger.info("MedicareServiceImpl.queryAlipayMedicareTest.resCommon -> {}", JSON.toJSONString(resCommon));
        response.setResultCodeAndMessageAndResult(resCommon.getResultCode(), resCommon.getResultMessage(), resCommon.getResult());
        return response;
    }

    private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIgHnOn7LLILlKETd6BFRJ0GqgS2Y3mn1wMQmyh9zEyWlz5p1zrahRahbXAfCfSqshSNfqOmAQzSHRVjCqjsAw1jyqrXaPdKBmr90DIpIxmIyKXv4GGAkPyJ/6FTFY99uhpiq0qadD/uSzQsefWo0aTvP/65zi3eof7TcZ32oWpwIDAQAB";

    private static final String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKK0PXoLKnBkgtOl0kvyc9X2tUUdh/lRZr9RE1frjr2ZtAulZ+Moz9VJZFew1UZIzeK0478obY/DjHmD3GMfqJoTguVqJ2MEg+mJ8hJKWelvKLgfFBNliAw+/9O6Jah9Q3mRzCD8pABDEHY7BM54W7aLcuGpIIOa/qShO8dbXn+FAgMBAAECgYA8+nQ380taiDEIBZPFZv7G6AmT97doV3u8pDQttVjv8lUqMDm5RyhtdW4n91xXVR3ko4rfr9UwFkflmufUNp9HU9bHIVQS+HWLsPv9GypdTSNNp+nDn4JExUtAakJxZmGhCu/WjHIUzCoBCn6viernVC2L37NL1N4zrR73lSCk2QJBAPb/UOmtSx+PnA/mimqnFMMP3SX6cQmnynz9+63JlLjXD8rowRD2Z03U41Qfy+RED3yANZXCrE1V6vghYVmASYsCQQCoomZpeNxAKuUJZp+VaWi4WQeMW1KCK3aljaKLMZ57yb5Bsu+P3odyBk1AvYIPvdajAJiiikRdIDmi58dqfN0vAkEAjFX8LwjbCg+aaB5gvsA3t6ynxhBJcWb4UZQtD0zdRzhKLMuaBn05rKssjnuSaRuSgPaHe5OkOjx6yIiOuz98iQJAXIDpSMYhm5lsFiITPDScWzOLLnUR55HL/biaB1zqoODj2so7G2JoTiYiznamF9h9GuFC2TablbINq80U2NcxxQJBAMhw06Ha/U7qTjtAmr2qAuWSWvHU4ANu2h0RxYlKTpmWgO0f47jCOQhdC3T/RK7f38c7q8uPyi35eZ7S1e/PznY=";

}
